package com.example.work6.
public class MainActivity extends AppCompatActivity {
    @BindView(R.id.main_content) TextView main_content;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==0x1234){
                    main_content.setText(main_content.getText().toString()+msg.getData().getString("content"));
                }
            }};
        new Thread(new UdpServer(handler)).start();
        @BindView(R.id.et_main_content) EditText et_main_content;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
            new Thread(new ClientThread()).start();
        }
        @OnClick(R.id.btn_main_send)
        void send(){
            Message msg=new Message();
            msg.what=0x1234;
            Bundle bundle =new Bundle();
            bundle.putString("sendContent",et_main_content.getText().toString());
            msg.setData(bundle);
            ClientThread.sendHandler.sendMessage(msg);
        }
        class ClientThread implements Runnable{
            DatagramSocket remoteDs=null;
            InetAddress remoteAddr=null;
            private final static int remotePort=5000;
            byte[] buf=new byte[1024];
            public static Handler sendHandler;
            public ClientThread(){
                try {
                    remoteDs=new DatagramSocket();
                    remoteAddr= InetAddress.getByName("127.0.0.1");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void run() {
                new Thread(){@Override
                public void run() {
                    Looper.prepare();
                    sendHandler=new Handler(){
                        @Override
                        public void handleMessage(Message msg) {
                            if(msg.what==0x1234){
                                byte[] buffer=msg.getData().getString("sendContent").getBytes();
                                DatagramPacket remoteDp=new DatagramPacket(buffer,buffer.length,remoteAddr,remotePort);
                                try {
                                    remoteDs.send(remoteDp);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    };
                    Looper.loop();
                }
                }.start();
            }

        }
    }
}
